package com.chat.http.service;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.chat.constant.sys.ResourceConstant;
import com.chat.dao.ChatPeopleRelationDao;
import com.chat.dao.IGroupDao;
import com.chat.entity.TdChatGroup;
import com.chat.vo.params.ExceptionVo;

import sun.misc.Lock;

/**
 * 群聊基本业务
 * 
 * @author lwh
 *
 */
@Service
public class GroupManageService {
	private static final Logger logger = Logger.getLogger(GroupManageService.class);

	@Autowired
	private ChatPeopleRelationDao peopleRelationDao;

	@Autowired
	private IGroupDao groupDao;

	/**
	 * 建群业务
	 * 
	 * @param fromUser
	 * @param inviteUsers
	 * @param groupName
	 * @return
	 * @throws ExceptionVo 
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public TdChatGroup createGroup(String fromUser, String[] inviteUsers, String groupName) throws ExceptionVo {
		logger.info("进入建群业务");
		List<String> inviteUsersList = Arrays.asList(inviteUsers);
		String friends = peopleRelationDao.getAllFriendByUserName(fromUser);
		logger.info("用户"+ fromUser +"的好友：" + friends );
		
		if (null != friends) {
			String[] friendsArray = friends.split(",");
			List<String> friendsList = Arrays.asList(friendsArray);

			// 校验邀请入群人员是否为用户的好友
			for (String inviteTemp : inviteUsersList) {
				if (false == friendsList.contains(inviteTemp)) {
					logger.info("用户"+ fromUser +"和"+ inviteTemp +"不是好友关系");
					return null;
				}
			}
			StringBuffer strb = new StringBuffer();
			strb.append(fromUser).append(",");
			for (int i = 0; i < inviteUsers.length; i++) {
				strb.append(inviteUsers[i]);
				if (i != inviteUsers.length - 1) {
					strb.append(",");
				}
			}
			TdChatGroup group = new TdChatGroup();
			//加锁，防止高并发下，产生相同的时间擢
			Lock lock = new Lock();
			try {
				lock.lock();
				group.setGroupid(String.valueOf(new Date().getTime()));
			} catch (InterruptedException e) {
				throw new ExceptionVo("网络堵车，请稍后重试");
			}finally{
				lock.unlock();
			}
			group.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			group.setGroupadmin(fromUser);
			group.setGroupname(groupName);
			group.setGroupusers(strb.toString());
			//群人数：邀请人数 + 群主
			group.setUsernum(inviteUsers.length + 1);
			group.setGroupheadimg(ResourceConstant.GroupHeadImg.getVal());
			groupDao.insertGroup(group);
			return group;
		}
		return null;
	}

	/**
	 * 获取“群”详情
	 * @param groupid(http)
	 */
	public void getGroupDetails(String groupid){
		
	}
	
	/**
	 * 修改群信息(群名称、群头像、群主)(http + ws)
	 */
	public void modifyGroupDetails() {

	}
	
	/**
	 * 发送群信息(http+ws)
	 */
	public void sendGroupMsg(){
		
	}
	
}
